package edu.drawingDice;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;

import java.awt.event.*;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Die extends JPanel {

	private static final Random RNG = new Random();
	private static final Dimension SIZE = new Dimension(48, 48);

	private Color color;
	private int value = RNG.nextInt(6) + 1;
	private boolean active = false;

	public Die() {
		this(Color.WHITE);
	}

	public Die(Color color) {
		this.color = color;
		this.setPreferredSize(SIZE);
	}

	public void roll() {
		if (!active)
			return;
		value = RNG.nextInt(6) + 1;
		repaint();
	}

	public int getValue() {
		return value;
	}

	public void setValue(int value) throws IllegalArgumentException {
		if (value > 0 && value <= 6)
			this.value = value;
		else
			throw new IllegalArgumentException(value
					+ " is not in the range (1-6)");
	}

	public void activate() {
		active = true;
	}

	public void deactivate() {
		active = false;
	}

	public boolean isActive() {
		return active;
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		setBackground(color);

		g.drawRoundRect(0, 0, 50, 50, 5, 5);

		switch (value) {
		case 1:
			g.fillOval(21, 21, 6, 6);
			break;
		case 4:
			g.fillOval(13, 29, 6, 6);
			g.fillOval(29, 13, 6, 6);
		case 2:
			g.fillOval(13, 13, 6, 6);
			g.fillOval(29, 29, 6, 6);
			break;
		case 5:
			g.fillOval(9, 33, 6, 6);
			g.fillOval(33, 9, 6, 6);
		case 3:
			g.fillOval(9, 9, 6, 6);
			g.fillOval(21, 21, 6, 6);
			g.fillOval(33, 33, 6, 6);
			break;
		case 6:
			g.fillOval(13, 9, 6, 6);
			g.fillOval(13, 21, 6, 6);
			g.fillOval(13, 33, 6, 6);

			g.fillOval(29, 9, 6, 6);
			g.fillOval(29, 21, 6, 6);
			g.fillOval(29, 33, 6, 6);
			break;

		default:
			System.out.println("Value out of bounds: " + value);
			break;

		}

	}

	public static void main(String args[]) {
		final Die dice[] = new Die[6];
		JButton roll = new JButton("Roll");
		JFrame f = new JFrame();

		roll.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				for (Die d : dice) {
					d.roll();
				}
			}
		});
		
		f.setLayout(new FlowLayout());
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		for(Die d : dice){
			d = new Die(new Color(
					(int) (Math.random() * 256), 
					(int) (Math.random() * 256), 
					(int) (Math.random() * 256)));
			d.setValue(RNG.nextInt(6) + 1);
			d.activate();
			f.add(d);
		}
		

		
		f.add(roll);
		
		f.pack();
		f.setVisible(true);
		
	}
}
